<template>
  <Teleport to="body">
    <div>
      <input ref="nInputRef" v-model="val" type="text" class="n-input" :style="style" @keyup.enter="confirm" @keyup.esc="cancel" @input="handleInput" />
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import * as PIXI from 'pixi.js'
import { ref, watch, computed, nextTick } from 'vue'
import stageModal, { stageModalInputSwitch } from '@/utils/stageModal'
import { getPixi, getPixiData } from '@/store/modules/usePixiStore'
const nInputRef = ref<HTMLInputElement | null>(null)
const props = defineProps({
  textUid: {
    required: true,
    type: Number,
  },
})
const modelValue = defineModel<Wx.Card.Diy>({
  required: true,
})

const attrName = computed(() => {
  const pixiData = getPixiData(props.textUid)
  return pixiData.attrName as string
})
const val = ref<string>('')
const oldVal = ref<string>('')
const displayStyle = ref({
  display: 'none',
})
const locationStyle = ref<Record<string, string | number>>({
  top: '40%',
  left: '50%',
  width: '20rem',
  height: '3rem',
})

const style = computed(() => {
  return { ...displayStyle.value, ...locationStyle.value }
})

watch(stageModalInputSwitch, val => {
  displayStyle.value.display = val ? 'block' : 'none'
  if (!val) {
    finish()
  }
})

const init = (
  text: string,
  param = {
    top: '40%',
    left: '50%',
    width: '20rem',
    height: '3rem',
  },
) => {
  stageModal() // 初始化透明蒙版
  stageModalInputSwitch.value = true
  val.value = text
  oldVal.value = text
  displayStyle.value.display = 'block'
  locationStyle.value.left = param.left
  locationStyle.value.top = param.top
  locationStyle.value.width = param.width
  locationStyle.value.height = param.height
  locationStyle.value.lineHeight = param.height
  nextTick(() => {
    nInputRef.value?.focus()
  })
}

const confirm = () => {
  stageModalInputSwitch.value = false
}

const cancel = () => {
  val.value = oldVal.value
  modelValue.value[attrName.value as Wx.Card.DiyText] = val.value
  stageModalInputSwitch.value = false
}

const handleInput = () => {
  modelValue.value[attrName.value as Wx.Card.DiyText] = val.value
}

const finish = () => {
  const text = getPixi(props.textUid) as PIXI.Text
  if (text) {
    text.text = val.value
  }
  return val.value
}
defineExpose({
  init,
  finish,
})
</script>

<style scoped lang="scss">
.n-input {
  position: fixed;
  // top: 40%;
  // left: 50%;
  // transform: translate(-50%, -50%);
  // width: 20rem;
  // height: 3rem;
  // line-height: 3rem;
  font-size: 2rem;
  font-family: 'RZFont';
  border: none;
  text-align: center;
  border-radius: 0.5rem;
  background-color: #efd9af;
  &:focus {
    outline: none;
    // caret-color: transparent;
  }
}
</style>
